<template>
  <div class='container'>
    <el-card>
      <span>陈晓东</span>
      <!-- 头部新增试题 -->
      <div>
        <page-tools>
          <template v-slot:before>
            <span class="text">说明:目前支持学科和关键字条件筛选</span>
          </template>
          <template v-slot:after>
            <el-button size="small" icon="el-icon-edit" type="success" @click="$router.push('new')">新增试题</el-button>
          </template>
        </page-tools>
        <!-- 新增试题表单 -->
        <el-form ref="quesitonsForm">
          <el-row>
            <el-col :span="6">
              <el-form-item label="学科" label-width="80px">
                <el-select v-model="form.subjectID" placeholder="请选择" @focus="clickedSubject" @change="onChangedSubject">
                  <el-option
                    v-for="item in subjectList"
                    :key="item.id"
                    :label="item.subjectName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="二级目录" label-width="80px">
                <el-select placeholder="请选择" v-model="form.catalogID">
                  <el-option
                    v-for="item in catalogListForSubject"
                    :key="item.id"
                    :label="item.directoryName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="标签" label-width="80px">
                <el-select placeholder="请选择" v-model="form.tags">
                  <el-option
                    v-for="item in tagsLsitForSubject"
                    :key="item.id"
                    :label="item.tagName"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="关键字" label-width="80px">
                <el-input v-model="form.keyword"></el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="试题类型" label-width="80px">
                <el-select placeholder="请选择" v-model="form.questionsType">
                  <el-option
                    v-for="item in questionType"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="难度" label-width="80px">
                <el-select placeholder="请选择" v-model="form.difficulty">
                  <el-option
                    v-for="item in difficulty"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="方向" label-width="80px">
                <el-select placeholder="请选择" v-model="form.direction">
                  <el-option
                    v-for="item in direction"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="录入人" label-width="80px">
                <el-select placeholder="请选择" v-model="form.creatorID" @focus="clickedCreator">
                  <el-option
                    v-for="item in creatorList"
                    :key="item.id"
                    :label="item.username"
                    :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="6">
              <el-form-item label="题目备注" label-width="80px">
                <el-input v-model="form.remarks"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="企业简称" label-width="80px">
                <el-input v-model="form.shortName"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="城市" label-width="80px">
                <el-select @focus="clickedCity" @change="changedCity" v-model="form.province" class="city-select-left" size="small" placeholder="请选择">
                  <el-option
                    v-for="item in citys"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
                <el-select v-model="form.city" class="city-select-right" size="small" placeholder="请选择">
                  <el-option
                    v-for="item in area"
                    :key="item"
                    :label="item"
                    :value="item">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6" class="btn">
              <el-form-item>
                <el-button @click="onClear" szie="small">清除</el-button>
                <el-button type="primary" size="small" @click="searchQuestions">搜索</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <!-- 显示数据条数 -->
      <div class="data-text">
        <page-tools>
          <template v-slot:icon>
            <i class="el-icon-info" />
          </template>
          <template v-slot:before>
            <span class="data-total">数据一共 {{ total }} 条</span>
          </template>
        </page-tools>
      </div>
      <!-- 数据表格 -->
      <el-table
        :data="tableData"
        style="width: 100%">
        <el-table-column
          prop="number"
          label="试题编号"
          width="120"/>
        <el-table-column
          prop="subject"
          label="学科"
          width="180"/>
        <el-table-column
          prop="catalog"
          width="180"
          label="目录"/>
        <el-table-column
          prop="questionType"
          width="180"
          label="题型"/>
        <el-table-column
          prop="question"
          label="题干"
          width="280"/>
        <el-table-column
          prop="addDate"
          width="180"
          label="录入时间"/>
        <el-table-column
          prop="difficulty"
          width="180"
          label="难度"/>
        <el-table-column
          prop="creator"
          width="180"
          label="录入人"/>
        <el-table-column
          label="操作">
          <template v-slot="{ row }">
            <el-button type="primary" size="small" icon="el-icon-view" circle @click="preview(row)" />
            <el-button type="success" size="small" icon="el-icon-edit" @click="$router.push('new/?id=' + row.id )" circle></el-button>
            <el-button type="danger" size="small" icon="el-icon-delete" circle @click="deleteQuestions(row)"></el-button>
            <el-button type="warning" size="small" icon="el-icon-check" circle @click="addChoice(row)"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination @pageChange="getQuestionList" :total="total" :paginationPage.sync="page.page" :paginationPagesize.sync="page.pagesize" />
    </el-card>
    <questions-preview :dialogVisible.sync="questionPreviewDialog" :row="questionsDetail" />
  </div>
</template>

<script>
import { difficulty, questionType, direction } from '@/api/hmmm/constants'
import pageTools from '../components/page-tools.vue'
import { list, detail, remove, choiceAdd } from '@/api/hmmm/questions.js'
import { html2Text, parseTime } from '../../utils'
import pagination from '../components/pagination'
import questionsPreview from '../components/questions-preview.vue'
import { list as subjectList } from '@/api/hmmm/subjects.js'
import { list as catalogList } from '@/api/hmmm/directorys.js'
import { list as tagList } from '@/api/hmmm/tags.js'
import { simple as userSimpleList } from '@/api/base/users'
import { provinces, citys } from '@/api/hmmm/citys'
export default {
  components: {
    pageTools,
    pagination,
    questionsPreview
  },
  data () {
    return {
      page: {
        page: 1,
        pagesize: 20
      },
      tableData: [], // 表格渲染数据
      total: 0, // 题目数量
      questionPreviewDialog: false, // 题目预览对话框显示
      questionsDetail: {},
      subjectList: [], // 学科列表
      catalogListForSubject: [], // 学科对应下的目录
      tagsLsitForSubject: [], // 学科对应下的标签
      form: {
        subjectID: '',
        catalogID: '',
        tags: '',
        questionsType: '',
        difficulty: '',
        direction: '',
        creatorID: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      },
      difficulty,
      questionType,
      direction,
      creatorList: [],
      citys: [],
      area: []
    }
  },
  async created () {
    await this.getQuestionList()
  },
  methods: {
    // 获取题库列表
    async getQuestionList () {
      const { data } = await list(this.page)
      this.page.page = data.page
      this.tableData = this.formatData(data.items)
      this.total = data.counts
    },
    // 处理数据
    formatData (data) {
      return data.map(item => {
        item.answer = html2Text(item.answer)
        item.difficulty = difficulty.find(item1 => +item.difficulty === item1.value).label
        item.questionType = questionType.find(item2 => +item.questionType === item2.value).label
        item.addDate = parseTime(item.addDate)
        item.question = html2Text(item.question)
        return item
      })
    },
    // 题目预览
    async preview (row) {
      const { data } = await detail({
        id: row.id
      })
      data.options = this.sortOption(data.options)
      this.questionsDetail = {
        ...this.formatData([data])[0]
      }
      this.questionPreviewDialog = true
    },
    // 对后台返回的选项数组进行排序
    sortOption (data) {
      const newOptionArr = data.map(item => {
        item.code = item.code.charCodeAt()
        return item
      })
      const sortOptionArr = newOptionArr.sort(this.compare('code'))
      const formatOptinArr = sortOptionArr.map(item => {
        item.code = String.fromCharCode(item.code)
        return item
      })
      return formatOptinArr
    },
    compare (property) {
      return function (a, b) {
        const value1 = a[property]
        const value2 = b[property]
        return value1 - value2
      }
    },
    // 点击了学科下拉
    async clickedSubject () {
      const { data } = await subjectList()
      this.subjectList = data.items
    },
    // 选择了学科
    async onChangedSubject (value) {
      const { data } = await catalogList({ subjectName: value })
      this.catalogListForSubject = data.items
      const { data: cataData } = await tagList({ subjectName: value })
      this.tagsLsitForSubject = cataData.items
    },
    // 点击了录入人
    async clickedCreator () {
      const { data } = await userSimpleList()
      this.creatorList = data
    },
    // 点击了城市
    clickedCity () {
      this.citys = provinces()
    },
    // 选择了城市
    changedCity (value) {
      this.area = citys(value)
      this.form.city = this.area[0]
    },
    // 清除表单
    onClear () {
      this.form = {
        subjectID: '',
        catalogID: '',
        tags: '',
        questionsType: '',
        difficulty: '',
        direction: '',
        creatorID: '',
        remarks: '',
        shortName: '',
        province: '',
        city: ''
      }
      this.$refs.quesitonsForm.resetFields()
    },
    // 搜索题目
    async searchQuestions () {
      const { data } = await list(this.form)
      if (!data.items.length) return this.$message.info('暂未匹配到试题')
      this.tableData = this.formatData(data.items)
    },
    // 删除试题
    async deleteQuestions (row) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await remove({ id: row.id })
        // 更新当前页码
        const totalPage = Math.ceil((this.total - 1) / this.page.pagesize)
        const currentPage = this.page.page > totalPage ? totalPage : this.page.page
        this.page.page = this.page.page < 1 ? 1 : currentPage
        await this.getQuestionList()
        this.$message({
          type: 'success',
          message: '删除成功!'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 加入精选
    async addChoice (row) {
      this.$confirm('此操作将该试题加入精选,是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        await choiceAdd({ id: row.id, choiceState: 1 })
        this.$message.success('加入精选成功')
        await this.$router.push('choice')
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消加入'
        })
      })
    }
  }
}
</script>

<style scoped lang='less'>
.container {
  padding: 10px;
  .text {
    font-size: 12px;
    color: pink;
  }
  .el-form {
    margin-top: 15px;
    .el-input, .el-select {
      width: 100%;
    }
    .city-select-left {
      width: 48%;
      margin-right: 2%;
    }
    .city-select-right {
      width: 50%;
    }
    .btn {
      display: flex;
      justify-content: flex-end;
    }
  }
  .data-text {
    height: 35px;
    line-height: 35px;
    font-size: 13px;
    color: #909399;
    padding: 0 0 0 10px;
    background-color: #f4f4f5;
    .el-icon-info {
      font-size: 16px;
    }
    .data-total {
      margin-left: 10px;
    }
  }
  .el-button--primary{
    color: #409eff;
    background: #ecf5ff;
    border-color: #b3d8ff;
    &:hover {
      background: #409eff;
      border-color: #409eff;
      color: #fff;
    }
  }
  .el-button--success {
    color: #67c23a;
    background: #f0f9eb;
    border-color: #c2e7b0;
    &:hover {
      background: #67c23a;
      border-color: #67c23a;
      color: #fff;
    }
  }
  .el-button--danger {
    color: #f56c6c;
    background: #fef0f0;
    border-color: #fbc4c4;
    &:hover {
      background: #f56c6c;
      border-color: #f56c6c;
      color: #fff;
    }
  }
  .el-button--warning {
    color: #e6a23c;
    background: #fdf6ec;
    border-color: #f5dab1;
    &:hover {
      background: #e6a23c;
      border-color: #e6a23c;
      color: #fff;
    }
  }
}
</style>
